package com.jsm.twentyfour.util;


import java.util.HashSet;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class UniqueDBIndexUtil {
    private static Long currentSeconds = getBaseTime();
    static CopyOnWriteArrayList <Integer> indexList = new CopyOnWriteArrayList();
    static BlockingQueue<Integer> indexPool = new LinkedBlockingQueue<>(10000);
    private static Random r = new Random();

    static {
        for (int i = 0; i < 10000; i++) {
            indexList.add(i);
            indexPool.add(i);
        }
    }

    public synchronized static void indexPoolInit() {
        indexPool.clear();
        for (Integer integer : indexList) {
            indexPool.add(integer);
        }
    }

    public synchronized static int getRandomIndex() {
        if (indexPool.size() <= 0) {
            indexPoolInit();
        }
        return indexPool.remove();
    }

    public static Long generate() {
        if (getBaseTime() > currentSeconds) {
            indexPoolInit();
            currentSeconds = getBaseTime();
        }

//        long postfix = (long) Math.floor(Math.random() * 10000);
        long finalIdx = currentSeconds * 10000 + getRandomIndex();
        return finalIdx;
    }

    public static long getBaseTime() {
        return DateUtil.now().getTime() / 1000 - 1483200000;
    }


//

}
